package com.bluemobi.framework.pay.wechat.service;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.lang.StringUtils;
import org.xml.sax.SAXException;

import com.alibaba.fastjson.JSON;
import com.bluemobi.framework.constant.SystemConstant;
import com.bluemobi.framework.pay.wechat.common.Configure;
import com.bluemobi.framework.pay.wechat.common.PayCommonUtil;
import com.bluemobi.framework.pay.wechat.entity.CloseOrderReq;
import com.bluemobi.framework.pay.wechat.entity.CloseOrderRes;

/**
 * 关闭订单service
 */
public class CloseorderService extends BasePayService {
	/**
	 * 初始化接口地址
	 */
	public CloseorderService() throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException,
			KeyStoreException, IOException, NoSuchProviderException {
		super(Configure.CLOSEORDER_URL);
	}

	/**
	 * 关闭订单（避免重复支付）
	 *
	 * @param coreq
	 *            关闭订单请求对象
	 * @return map
	 */
	public Map<String, Object> execute(CloseOrderReq coreq) {
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("status", SystemConstant.RETURN_STATUS_FAIL);
		try {
			if (StringUtils.isEmpty(coreq.getKey())) {
				coreq.setKey(Configure.APIKEY);
			}
			if (StringUtils.isEmpty(coreq.getAppid())) {
				coreq.setAppid(Configure.APPID);
			}
			if (StringUtils.isEmpty(coreq.getMch_id())) {
				coreq.setMch_id(Configure.MCH_ID);
			}
			if (StringUtils.isEmpty(coreq.getNonce_str())) {
				coreq.setNonce_str(PayCommonUtil.getNoncestr());
			}
			// 获取加密签名
			coreq.setSign(PayCommonUtil.getSign(coreq));
			if (StringUtils.isNotEmpty(coreq.getSign())) {
				String key = coreq.getKey();
				coreq.setKey(null);
				// 请求关闭订单接口
				try {
					String responseString = sendPost(coreq);
					try {
						CloseOrderRes cores = PayCommonUtil.getObjectFromXML(responseString, CloseOrderRes.class);
						if (cores.getReturn_code().equals(Configure.RETURN_CODE_SUCCESS)) {
							// 验证签名是否正确
							if (PayCommonUtil.checkIsSignValidFromResponseString(responseString, key)) {
								resultMap.put("status", SystemConstant.RETURN_STATUS_SUCCESS);
								resultMap.put("data", cores);
							} else {
								resultMap.put("msg", "回调签名验证失败");
								logger.error("回调签名验证失败:" + responseString);
							}
						} else {
							resultMap.put("msg", "关闭订单");
							logger.error("关闭订单：" + cores.getReturn_msg() + ";" + cores.getErr_code() + ":"
									+ cores.getErr_code_des() + ";原始返回数据:" + responseString);
						}
					} catch (ParserConfigurationException | IOException | SAXException e) {
						resultMap.put("msg", "验证支付回调sign异常");
						logger.error("验证支付回调sign异常:" + e.getMessage());
					}
				} catch (UnrecoverableKeyException | IOException | NoSuchAlgorithmException | KeyStoreException
						| KeyManagementException | NoSuchProviderException e) {
					resultMap.put("msg", "调用关闭订异常");
					logger.error("调用关闭订异常:参数" + JSON.toJSONString(coreq) + " 错误信息:" + e.getMessage());
				}
			} else {
				resultMap.put("msg", "签名错误");
				logger.error("签名错误：无签名信息");
			}
		} catch (IllegalAccessException e) {
			resultMap.put("msg", "关闭订前,签名异常");
			logger.error("关闭订前,签名异常：" + e.getMessage());
		}
		return resultMap;
	}

	public static void main(String[] args) throws UnrecoverableKeyException, NoSuchAlgorithmException,
			KeyManagementException, KeyStoreException, NoSuchProviderException, IOException {
		CloseOrderReq closeOrderReq = new CloseOrderReq();
		closeOrderReq.setOut_trade_no("20160");
		Map<String, Object> execute = new CloseorderService().execute(closeOrderReq);
		System.out.println(JSON.toJSONString(execute));
	}
}
